/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package editorRozpisu;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import strukturaRozpis.Rozpis;
import strukturaRozpis.Sluzba;
import strukturaZamestnanciNepritomnost.Zamestnanci;

/**
 *
 * @author Ondrej
 */
public class CreatePDF {

    private static Font catFont = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
    private static Font redFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.RED);
    private static Font subFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
    private static Font smallBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
    final String[] MONTHS = {"januar", "februar", "marec", "april", "maj", "jun", "jul", "august", "september", "oktober", "november", "december"};
    final String[] DAYS_OF_WEEK = {"Nedela", "Pondelok", "Utorok", "Streda", "Stvrtok", "Piatok", "Sobota"};
    final float PADDING = 2;
    Zamestnanci zamestnanci;
    Rozpis rozpis;

    /**
     *
     * @param rozpis
     * @param zamestnanci
     */
    public CreatePDF(Rozpis rozpis, Zamestnanci zamestnanci) {
        this.zamestnanci = zamestnanci;
        this.rozpis = rozpis;
    }

    /**
     *
     * @param name
     * @return
     */
    public Document generatePDF(String name) {
        Document document = new Document();
        try {
            PdfWriter.getInstance(document, new FileOutputStream(name));
            document.open();
            addMetaData(document);
            addContent(document);
            document.close();
        } catch (FileNotFoundException | DocumentException e) {
            return null;
        }
        return document;
    }

    public boolean savePDF(String path) {
        if (generatePDF(path) == null) {
            return false;
        }
        return true;
    }

    private void addMetaData(Document document) {
        document.addTitle("Mesacny rozpis sluzieb pre vratnice FMFI na mesiac" + MONTHS[rozpis.getMonth() - 1]);
        document.addSubject("Using iText");
        document.addKeywords("Rozpis sluzieb");
        document.addAuthor("tis-unknown");
        document.addCreator("Ondrej Balun");
    }

    private void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(" "));
        }
    }

    private void addContent(Document document) throws DocumentException {
        Paragraph preface = new Paragraph();
        addEmptyLine(preface, 1);

        // Lets write a big header
        preface.add(new Paragraph("Mesacny rozpis sluzieb FMFI na mesiac " + MONTHS[rozpis.getMonth() - 1] + " " + rozpis.getYear(), catFont));

        addEmptyLine(preface, 1);
        // Will create: Report generated by: _name, _date
        preface.add(new Paragraph("Report generated by: " + "tis-unknown" + ", " + Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + ". " + MONTHS[Calendar.getInstance().get(Calendar.MONTH)] + " " + Calendar.getInstance().get(Calendar.YEAR), smallBold));
        addEmptyLine(preface, 3);
        createTable(preface);
        document.add(preface);
//        Anchor anchor = new Anchor(MONTHS[rozpis.getMonth() - 1] + " " + rozpis.getYear(), catFont);
//        anchor.setName(MONTHS[rozpis.getMonth()] + " " + rozpis.getYear());

        // Second parameter is the number of the chapter
//        Chapter catPart = new Chapter(new Paragraph(anchor), 1);
//        Chapter catPart = new Chapter(1);
//        Section subCatPart = catPart.addSection(preface);

//        document.add(catPart);
//        document.add(subCatPart);
    }

    private void createTable(Paragraph p) throws BadElementException, DocumentException {
        PdfPTable table = new PdfPTable(7);
                    float[] columnWidths = new float[] {17f, 17f, 10f, 19f, 19f, 19f, 19f};
            table.setWidths(columnWidths);

        PdfPCell c1 = new PdfPCell(new Phrase("Datum", subFont));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPadding(PADDING);
        c1.setVerticalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Den", subFont));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPadding(PADDING);
        c1.setVerticalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Cas", subFont));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPadding(PADDING);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("pavilon M", subFont));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPadding(PADDING);
        c1.setColspan(2);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("pavilon F1", subFont));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        c1.setPadding(PADDING);
        c1.setColspan(2);
        table.addCell(c1);

        table.setHeaderRows(1);
        for (Map.Entry<Integer, ArrayList<Sluzba>> elem : rozpis.getRozpis().entrySet()) {
            int den = elem.getKey();
            ArrayList<Sluzba> sluzby = elem.getValue();

            // denna
            // tucne ak je vikend
            if (DAYS_OF_WEEK[sluzby.get(0).getCalendar().get(Calendar.DAY_OF_WEEK) - 1].equals(DAYS_OF_WEEK[0]) || DAYS_OF_WEEK[sluzby.get(0).getCalendar().get(Calendar.DAY_OF_WEEK) - 1].equals(DAYS_OF_WEEK[6])) {
                table.addCell(new Phrase(String.valueOf(den) + ".", redFont));
                table.addCell(new Phrase(DAYS_OF_WEEK[sluzby.get(0).getCalendar().get(Calendar.DAY_OF_WEEK) - 1], redFont));
            } else {
                table.addCell(String.valueOf(den) + ".");
                table.addCell(DAYS_OF_WEEK[sluzby.get(0).getCalendar().get(Calendar.DAY_OF_WEEK) - 1]);
            }
            table.addCell(sluzby.get(0).getCas());
            for (int i = 1; i >= 0; i--) {
                if (i == 1) {
                    table.addCell(zamestnanci.getZamestnanciAll().get(sluzby.get(i).getID_zam1()).getPriezvisko());
                    table.addCell(zamestnanci.getZamestnanciAll().get(sluzby.get(i).getID_zam2()).getPriezvisko());
                } else {
                    table.addCell(zamestnanci.getZamestnanciAll().get(sluzby.get(i).getID_zam1()).getPriezvisko());
                    if(sluzby.get(i).getID_zam2() == 0) {
                        table.addCell("-");
                    } else {
                        table.addCell(zamestnanci.getZamestnanciAll().get(sluzby.get(i).getID_zam2()).getPriezvisko());
                    }
                }
            }

            // nocna         
            // tucne ak je vikend
            if (DAYS_OF_WEEK[sluzby.get(0).getCalendar().get(Calendar.DAY_OF_WEEK) - 1].equals(DAYS_OF_WEEK[0]) || DAYS_OF_WEEK[sluzby.get(0).getCalendar().get(Calendar.DAY_OF_WEEK) - 1].equals(DAYS_OF_WEEK[6])) {
                table.addCell(new Phrase(String.valueOf(den) + ".", redFont));
                table.addCell(new Phrase(DAYS_OF_WEEK[sluzby.get(0).getCalendar().get(Calendar.DAY_OF_WEEK) - 1], redFont));
            } else {
                table.addCell(String.valueOf(den) + ".");
                table.addCell(DAYS_OF_WEEK[sluzby.get(0).getCalendar().get(Calendar.DAY_OF_WEEK) - 1]);
            }
            table.addCell(sluzby.get(2).getCas());
            for (int i = 3; i >= 2; i--) {
                table.addCell(zamestnanci.getZamestnanciAll().get(sluzby.get(i).getID_zam1()).getPriezvisko());
                table.addCell(zamestnanci.getZamestnanciAll().get(sluzby.get(i).getID_zam2()).getPriezvisko());
            }
        }
        p.add(table);

    }

    public static boolean uploadFile(String name) {

        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession("vratnica", "kempelen.ii.fmph.uniba.sk", 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword("Dumbier2012");
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.cd("/var/www/vratnica/rozpisy");
            File f = new File(name);
            FileInputStream fs = new FileInputStream(f);
            sftpChannel.put(fs, f.getName());
            fs.close();

            sftpChannel.exit();
            session.disconnect();
        } catch (IOException ex) {
            Logger.getLogger(CreatePDF.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JSchException e) {
            e.printStackTrace();
            return false;
        } catch (SftpException e) {
            e.printStackTrace();
            return false;
        } 
        return true;
    }
}
